from multiprocessing import Process
from mysql.connector.pooling import MySQLConnectionPool

class DBUtil(object):
    _pool = MySQLConnectionPool(pool_name="mypool", pool_size=10,
                                host="localhost", port="16033", user="root",
                                password="prs7000.sunri", database="vpShereManager")

    @classmethod
    def get_conn(cls):
        return cls._pool.get_connection()

    @staticmethod
    def close_conn(conn, cursor):
        if cursor:
            cursor.close()
        if conn:
            conn.close()

    @classmethod
    def select_one(cls, sql, params=None):
        conn = None
        cursor = None
        res = None
        try:
            conn = cls.get_conn()
            cursor = conn.cursor(dictionary=True)
            cursor.execute(sql,params)
            res = cursor.fetchone()
        except Exception as err:
            print("查询sql错误: ", str(err))
        finally:
            cls.close_conn(conn, cursor)
            return res

    @classmethod
    def select_all(cls, sql, params=None):
        conn = None
        cursor = None
        res = None
        try:
            conn = cls.get_conn()
            cursor = conn.cursor(dictionary=True)
            cursor.execute(sql,params)
            res = cursor.fetchall()
        except Exception as err:
            print("查询sql错误: ", str(err))
        finally:
            cls.close_conn(conn, cursor)
            return res

    @classmethod
    def uid_db(cls, sql, params=None):
        conn = None
        cursor = None
        try:
            conn = cls.get_conn()
            cursor = conn.cursor(dictionary=True)
            cursor.execute(sql,params)
            conn.commit()
        except Exception as err:
            if conn:
                conn.rollback()
            print("增删改 SQL 执行失败: ", str(err))
        finally:
            cls.close_conn(conn, cursor)

def worker():
    res = DBUtil.select_one("select * from config;")
    print("查询结果为：", res)

    all_res = DBUtil.select_all("select * from servers where id = 1;")
    print("所有查询结果为：", all_res)


if __name__ == '__main__':
    # processes = []
    # for i in range(60):
    #     p = Process(target=worker)
    #     processes.append(p)
    #     p.start()

    # for p in processes:
    #     p.join()
    xx = DBUtil.select_all("select * from system_config;")
    if not xx:
        print("查询结果为空")
    print(xx)